# flask web 网络编程文件
from flask import Flask, render_template, request,escape
from vsearch import log_request
import weather
import logging
# html 调用方法：render_template  按照 jinja2 规则
def log_request(req: 'flask_request',res: str) -> None:
    with open('weather.log','a')as log:

        print(req.form, req.remote_addr,req.user_agent,res,file=log,sep=" | ")
# print(str(dir(req)),res,file=log)
wu_key='513aa007abc35c285a648025471ee1f1'
app = Flask(__name__)


@app.route('/search4', methods=['GET'])
# 这些数据来自哪里？
def results() -> 'html':
    city = request.form['city']
    key = request.form['key']
    title = '这是您的查询结果:'
    results = str(weather.all(key, city,output='JSON', extensions='base'))
    log_request(request,results)

    return render_template('results.html',
                           the_title=title,
                           the_city=city,
                           the_results=results,
                           the_weather=weather,)


@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    title = '大家来查询想要了解的城市天气状况吧~'
    return render_template('entry.html',
                           the_title=title)

handler = logging.FileHandler('vsearch.log',encoding='UTF-8')
app.logger.addHandler(handler)

@app.route('/log')
def view_the_log() -> 'html':
    contents = []
    with open('weather.log','r') as log:
        for line in log:
            contents.append([])
            for item in line.split(' | '):
                contents[-1].append(escape(item))
    titles = ('用户提交','远程地址','访问代理','用户结果')
    return render_template('log.html',
                           the_title='日志系统',
                           the_row_titles=titles,
                           the_data=contents,)

if __name__ == '__main__':
	app.run(debug=True)

